 

package com.zdkj.admin.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.dto.UserDTO;
import com.zdkj.admin.api.entity.SysDept;
import com.zdkj.admin.api.entity.SysRole;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.admin.api.entity.SysUserImportlog;
import com.zdkj.admin.api.feign.RemoteSupportService;
import com.zdkj.admin.service.SysDeptService;
import com.zdkj.admin.service.SysRoleService;
import com.zdkj.admin.service.SysUserService;
import com.zdkj.admin.service.SysUserImportlogService;
import com.zdkj.admin.util.RegExUtilOrString;
import com.zdkj.admin.util.UploadDataListener;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.exception.CheckedException;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author cui_com
 * @date 2018/12/16
 */
@RestController
@AllArgsConstructor
@RequestMapping("/user")
@Api(value = "user", tags = "用户管理模块")
public class SysUserController {
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
	private static final Logger LOGGER = LoggerFactory.getLogger(SysUser.class);
	private final SysUserService userService;
	private final SysDeptService sysDeptService;
	private final RemoteSupportService remoteSupportService;
	private final SysRoleService sysRoleService;
	private final SysUserImportlogService sysUserImportlogService;

	private static final String defaultPassword = "Dt123456!@"; 

	/**
	 * 获取当前用户全部信息
	 *
	 * @return 用户信息
	 */
	@GetMapping(value = {"/info"})
	public R info() {
		String username = SecurityUtils.getUser().getUsername();
		SysUser user = userService.getOne(Wrappers.<SysUser>query()
				.lambda().eq(SysUser::getUsername, username));
		if (user == null) {
			return R.failed(null, "获取当前用户信息失败");
		}
		if(!user.getBelongToLine() && ObjectUtil.isNotEmpty(user.getLineCode()) && ObjectUtil.isEmpty(user.getStationCode())){
			String name = remoteSupportService.getLnameAndSnameByCode(user.getLineCode(),"abc").getData();
			if(StringUtils.isNotEmpty(name)){
				String[] split = name.split(",");
				user.setLineName(split[0]);
			}
		}
		if(!user.getBelongToLine() && ObjectUtil.isNotEmpty(user.getLineCode()) && ObjectUtil.isNotEmpty(user.getStationCode())){
			String name = remoteSupportService.getLnameAndSnameByCode(user.getLineCode(),user.getStationCode()).getData();
			if(StringUtils.isNotEmpty(name)){
				String[] split = name.split(",");
				user.setLineName(split[0]);
				user.setStationName(split[1]);
			}
		}
		return R.ok(userService.findUserInfo(user));
	}

	/**
	 * 获取指定用户全部信息
	 *
	 * @return 用户信息
	 */
	@Inner
	@GetMapping("/info/{username}")
	public R info(@PathVariable String username) {
		SysUser user = userService.getOne(Wrappers.<SysUser>query()
				.lambda().eq(SysUser::getUsername, username));
		if (user == null) {
			return R.failed(null, String.format("用户信息为空 %s", username));
		}
		return R.ok(userService.findUserInfo(user));
	}

	/**
	 * 通过ID查询用户信息
	 *
	 * @param id ID
	 * @return 用户信息
	 */
	@GetMapping("/{id}")
	public R user(@PathVariable Integer id) {
		return R.ok(userService.selectUserVoById(id));
	}

	/**
	 * 根据用户名查询用户信息
	 *
	 * @param username 用户名
	 * @return
	 */
	@GetMapping("/details/{username}")
	public R user(@PathVariable String username) {
		SysUser condition = new SysUser();
		condition.setUsername(username);
		return R.ok(userService.getOne(new QueryWrapper<>(condition)));
	}

	/**
	 * 根据员工号查询用户信息
	 *
	 * @param usercode 员工号
	 * @return
	 */
	@GetMapping("/details/usercode/{usercode}")
	public R userCode(@PathVariable String usercode) {
		SysUser condition = new SysUser();
		condition.setUserCode(usercode);
		return R.ok(userService.getOne(new QueryWrapper<>(condition)));
	}

	/**
	 * 根据工号查询用户信息
	 *
	 * @param usercode 用户工号
	 * @return
	 */
	@GetMapping("/check/{usercode}/{password}")
	public R userByCode(@PathVariable String usercode,@PathVariable String password) {
		SysUser condition = new SysUser();
		condition.setUserCode(usercode);
		SysUser one = userService.getOne(new QueryWrapper<>(condition));
		if(one==null){
			return R.failed("用户名或密码错误");
		}
		return R.ok(ENCODER.matches(password,one.getPassword()));
	}

	/**
	 * 根据账号查询用户信息
	 *
	 * @param userAccount 用户工号
	 * @return
	 */
	@GetMapping("/check/account/{userAccount}/{password}")
	public R userByAccount(@PathVariable String userAccount,@PathVariable String password) {
		SysUser condition = new SysUser();
		condition.setUsername(userAccount);
		SysUser one = userService.getOne(new QueryWrapper<>(condition));
		if(one==null){
			return R.failed("用户名或密码错误");
		}
		return R.ok(ENCODER.matches(password,one.getPassword()));
	}


	/**
	 * 删除用户信息
	 *
	 * @param id ID
	 * @return R
	 */
	@SysLog("删除用户信息")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_user_del')")
	@ApiOperation(value = "删除用户", notes = "根据ID删除用户")
	@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "path")
	public R userDel(@PathVariable Integer id) {
		SysUser sysUser = userService.getById(id);
		return R.ok(userService.deleteUserById(sysUser));
	}

	/**
	 * 添加用户
	 *
	 * @param userDto 用户信息
	 * @return success/false
	 */
	@SysLog("添加用户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_user_add')")
	public R user(@Valid @RequestBody UserDTO userDto) {
		if(userDto.getPassword().equals(userDto.getUserCode())){
			throw new CheckedException("密码不能与员工号重复");
		}
		if(!sysDeptService.checkDeptById(userDto.getDeptId())){
			throw new CheckedException("该部门不存在或不可用");
		}
		if(StringUtils.isEmpty(userDto.getNikename())){
			userDto.setNikename(userDto.getUsername());
		}

		SysUser queryDeptUser = new SysUser();
		BeanUtils.copyProperties(userDto, queryDeptUser);

      if(!queryDeptUser.getBelongToLine() && ObjectUtil.isNotEmpty(queryDeptUser.getLineCode()) && ObjectUtil.isNotEmpty(queryDeptUser.getStationCode())){
			Map<String,String> mapDept= userService.getLineDeptInfoByCode(queryDeptUser.getLineCode());
			if(mapDept!=null){
			    String lineDeptId = mapDept.get("deptId");
				String lineName =  mapDept.get("lineName");
				String lineDeptName =  mapDept.get("deptName");
                if(!(String.valueOf(queryDeptUser.getDeptId())).equals(lineDeptId)){
				   throw new CheckedException(lineName+"的人员只能选择 "+lineDeptName+"  部门");
				}
			}
		}
		SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery()
				.eq(SysUser::getUserCode,userDto.getUserCode()));
		if(null != user){
			throw new CheckedException("员工号不可重复");
		}
		return R.ok(userService.saveUser(userDto));
	}

	/**
	 * 更新用户信息
	 *
	 * @param userDto 用户信息
	 * @return R
	 */
	@SysLog("更新用户信息")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_user_edit')")
	public R updateUser(@Valid @RequestBody UserDTO userDto) {
		if(!sysDeptService.checkDeptById(userDto.getDeptId())){
			throw new CheckedException("该部门不存在或不可用");
		}	
		//LOGGER.info("更新用户信息读取前台参数1:",userDto.getDeptId()+","+userDto.getBelongToLine()+","+userDto.getLineCode());
		
		if(userDto.getBelongToLine()==true){
			userDto.setLineCode("");
			userDto.setStationCode("");
		}else {
			if(StringUtils.isEmpty(userDto.getManagementLineStation())){
				userDto.setManagementLineStation("");
			}
			SysUser user = new SysUser();
		    BeanUtils.copyProperties(userDto, user);
			if(!user.getBelongToLine() && ObjectUtil.isNotEmpty(user.getLineCode()) && ObjectUtil.isNotEmpty(user.getStationCode())){				
				Map<String,String> mapDept= userService.getLineDeptInfoByCode(user.getLineCode());
				if(mapDept!=null){
					String lineDeptId = mapDept.get("deptId");
					String lineName =  mapDept.get("lineName");
					String lineDeptName =  mapDept.get("deptName");
					if(!(String.valueOf(user.getDeptId())).equals(lineDeptId)){
					   throw new CheckedException(lineName+"的人员只能选择 "+lineDeptName+"  部门");
					}
				}
		     }
		}
		return R.ok(userService.updateUser(userDto));
	}

	/**
	 * 分页查询用户
	 *
	 * @param page    参数集
	 * @param userDTO 查询参数列表
	 * @return 用户集合
	 */
	@GetMapping("/page")
	public R getUserPage(Page page, UserDTO userDTO) {
        if(!(userDTO.getFlag()!=null && "LC".equals(userDTO.getFlag()))){//非用户管理LC查询
		   if (!SecurityUtils.getUser().getBelongToLine()&&!"".equals(SecurityUtils.getUser().getStationCode())) {//车站用户查询
			userDTO.setLineCode(SecurityUtils.getUser().getLineCode());
			userDTO.setStationCode(SecurityUtils.getUser().getStationCode());			
		  }
		}else if(userDTO.getFlag()!=null && "LC".equals(userDTO.getFlag())){//用户管理LC查询
		   	userDTO.setLineCode(SecurityUtils.getUser().getLineCode());//只能查本线路的用户
			//userDTO.setDeptId(SecurityUtils.getUser().getDeptId());//只能查本部门的用户    1207去掉只查本部门的限制
		}else if(userDTO.getFlag()!=null && "JD".equals(userDTO.getFlag())){//用户管理机电查询
			userDTO.setDeptId(SecurityUtils.getUser().getDeptId());//只能查本部门的用户
		}
		List<String> dateConditionhs = new ArrayList<>();
		if(CollectionUtil.isNotEmpty(userDTO.getDates1())) {
			dateConditionhs = userDTO.getDates1();
		}
		if(ObjectUtil.isNotEmpty(dateConditionhs)){
			userDTO.setStartTime(dateConditionhs.get(0));
			userDTO.setEndTime(dateConditionhs.get(1));
		}
		return R.ok(userService.getUsersWithRolePage(page, userDTO));
	}

	/**
	 * 分页查询用户(SC)
	 *
	 * @param page    参数集
	 * @param userDTO 查询参数列表
	 * @return 用户集合(SC)
	 */
	@GetMapping("/pageSc")
	public R getUserPageSc(Page page, UserDTO userDTO) {
		userDTO.setFlag("SC");
		return R.ok(userService.getUsersWithRolePage(page, userDTO));
	}


	/**
	 * 营收日报查询用户
	 * @return 用户集合
	 */
	@GetMapping("/getSysUserToRevenue")
	public R getSysUserToRevenue() {
		SysUser sysUser = new SysUser();
		QueryWrapper<SysUser> queryWrapper = Wrappers.query(sysUser);
		queryWrapper.lambda().eq(SysUser::getLineCode, SecurityUtils.getUser().getLineCode());
		queryWrapper.lambda().eq(SysUser::getStationCode, SecurityUtils.getUser().getStationCode());
		return R.ok(userService.list(queryWrapper));
	}


	/**
	 * 分页查询用户(LC)
	 *
	 * @param page    参数集
	 * @param userDTO 查询参数列表
	 * @return 用户集合(LC)
	 */
	@GetMapping("/pageLc")
	public R getUserPageLc(Page page, UserDTO userDTO) {
		userDTO.setFlag("LC");
		if (!SecurityUtils.getUser().getBelongToLine()&&!"".equals(SecurityUtils.getUser().getLineCode())) {
			userDTO.setLineCode(SecurityUtils.getUser().getLineCode());			
		}
		return R.ok(userService.getUsersWithRolePage(page, userDTO));
	}

	/**
	 * 分页查询用户(ACC)
	 *
	 * @param page    参数集
	 * @param userDTO 查询参数列表
	 * @return 用户集合
	 */
	@GetMapping("/pageAcc")
	public R getUserPageAcc(Page page, UserDTO userDTO) {
		userDTO.setFlag("ACC");
		return R.ok(userService.getUsersWithRolePage(page, userDTO));
	}


	/**
	 *
	 * @return 用户集合
	 */
	@GetMapping("/page/byStation")
	@ApiOperation("本站用户列表")
	public R getUserPageByStation() {
		SysUser sysUser = new SysUser();
		sysUser.setStationCode(SecurityUtils.getUser().getStationCode());
		return R.ok(userService.list(Wrappers.query(sysUser).lambda().eq(SysUser::getStationCode,sysUser.getStationCode())));
	}

	/**
	 *
	 * @return 用户集合
	 */
	@GetMapping("/page/dict")
	@ApiOperation("本站用户列表")
	public R getAll() {
		return R.ok(userService.list());
	}

	/**
	 *
	 * @return 用户集合
	 */
	@GetMapping("/page/byStation/{stationCode}")
	@ApiOperation("本站用户列表")
	public R getUserPageByStation(@PathVariable("stationCode") String stationCode) {
		SysUser sysUser = new SysUser();
		sysUser.setStationCode(stationCode);
		return R.ok(userService.list(Wrappers.query(sysUser).lambda().eq(SysUser::getStationCode,sysUser.getStationCode())));
	}

	/**
	 * 修改个人信息
	 *
	 * @param userDto userDto
	 * @return success/false
	 */
	@SysLog("修改个人信息")
	@PutMapping("/edit")
	public R updateUserInfo(@Valid @RequestBody UserDTO userDto) {
		return userService.updateUserInfo(userDto);
	}

	/**
	 * @param username 用户名称
	 * @return 上级部门用户列表
	 */
	@GetMapping("/ancestor/{username}")
	public R listAncestorUsers(@PathVariable String username) {
		return R.ok(userService.listAncestorUsers(username));
	}

	@Inner
	@PutMapping("/lock/{username}")
	public R lockUser(@PathVariable String username) {
		return R.ok(userService.lockUser(username));
	}
	/**
	 * 导入用户信息
	 *
	 * @param file
	 * @return
	 */
	@ApiOperation(value = "导入用户信息", notes = "导入用户信息")
	@SysLog("导入用户信息")
	@PostMapping("/import")
	public R importExcel(@RequestParam("file") MultipartFile file) {
		try {
			EasyExcel.read(file.getInputStream(), SysUser.class,
					new UploadDataListener(userService, SysUser.class)).sheet().doRead();
			return R.ok("导入成功");
		} catch (IOException e) {
			return R.ok("导入失败");
		}
	}

	@ApiOperation(value = "批量修改用户密码", notes = "批量修改用户密码，设置为初始密码(ids用逗号分隔)")
	@SysLog("批量修改用户密码")
	@PutMapping("/updatePasswordBatch")
	//public R updatePasswordBatch(@RequestParam(name = "ids", required = false) String ids, @RequestParam("password") String password) {
	public R updatePasswordBatch(@RequestParam(name = "ids", required = true) String ids) {
		LambdaQueryWrapper<SysUser> lambdaQueryWrapper = Wrappers.<SysUser>lambdaQuery();
		if (StringUtils.isNotEmpty(ids)) {
			lambdaQueryWrapper.in(SysUser::getUserId, Arrays.asList(ids.split(",")));
		}
		List<SysUser> list = userService.list(lambdaQueryWrapper);
		list.forEach(obj -> {
			obj.setPassword(ENCODER.encode(defaultPassword));
			//userService.updateById(obj);
			userService.updateUserStatusPassword(obj);
		});
		return R.ok();
	}
	@ApiOperation(value = "批量修改用户状态", notes = "批量修改用户锁定状态(ids用逗号分隔)")
	@SysLog("批量修改用户状态")
	@PutMapping("/updateBatchLock")
	public R updateBatchLock(@RequestParam(name = "ids", required = true) String ids, @RequestParam("flag") String flag) {	
		LambdaQueryWrapper<SysUser> lambdaQueryWrapper = Wrappers.<SysUser>lambdaQuery();
		if (StringUtils.isNotEmpty(ids)) {
			lambdaQueryWrapper.in(SysUser::getUserId, Arrays.asList(ids.split(",")));
		}
		//flag ：  9 锁定  0：解锁   8 禁用   0 正常
		List<SysUser> list = userService.list(lambdaQueryWrapper);
		list.forEach(obj -> {
			obj.setLockFlag(flag);			
			//userService.updateById(obj);
			userService.updateUserStatusPassword(obj);
		});
		return R.ok();
	}
	/**
	 * 下载机电模板
	 * @param
	 * @return
	 * @throws
	 */
	@ApiOperation(value = "下载机电模板", notes = "下载机电模板")
	@GetMapping("/exportTamplateJD")
	public void exportTamplateJD(HttpServletResponse response) {
		userService.exportTamplatesJD(response);
	}
	/**
	 * 导入机电用户信息
	 *
	 * @param file
	 * @return
	 */
	@ApiOperation(value = "导入机电用户信息", notes = "导入机电用户信息")
	@SysLog("导入机电用户信息")
	@PostMapping({ "/userImportJD" })
	public R userImportJD(@RequestParam("file") final MultipartFile file) throws Exception {

		final File excelFile = MultipartFileToFile.multipartFileToFile(file);
		List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();
		StringBuilder tipMessage = new StringBuilder();
		int iSucessCount = 0;
		int iErrorCount = 0 ;
		if (CollectionUtil.isNotEmpty(listMap)) {
			MultipartFileToFile.delteTempFile(excelFile);
			for (int m = 0; m < listMap.size(); m++) {
				Map<Integer, String> data = listMap.get(m);
				// 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
				LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

				UserDTO userDto = new UserDTO();

				if(StringUtils.isNotEmpty(data.get(1).trim())){

					//根据userCode先判断用户表中用户是否存在
					SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery()
							.eq(SysUser::getUsername, data.get(1).trim())
							.eq(SysUser::getDelFlag,"0"));
					//不存在添加
					if(ObjectUtil.isEmpty(user)){
						userDto.setNikename(data.get(0));//角色名
						userDto.setUsername(data.get(1).trim());
						userDto.setUserCode(data.get(1).trim());
						userDto.setPassword(defaultPassword);//默认密码

						Integer deptId = sysDeptJd(data);
						if(deptId == null){
							iErrorCount = iErrorCount+1;
							tipMessage.append("新增部门id为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setDeptId(deptId);//部门id

						userDto.setLockFlag("0");//账号锁定状态
						userDto.setBelongToLine(false);//默认不是线网人员

						String lineCode = lineCodeJd(data);
						if(StringUtils.isEmpty(lineCode)){
							iErrorCount = iErrorCount+1;
							tipMessage.append("新增线路编号为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setLineCode(lineCode);//管辖线路
						userDto.setStationCode("");//管辖站点默认空字符串
						userDto.setDeviceOperateNo("");//设备操作号默认空字符串

						List<Integer> roleList = roleListJd(data);
						userDto.setRole(roleList);//角色id
						userDto.setIsRecordChange("0");//不记录历史记录
						boolean isOk = userService.saveUser(userDto);
						if(isOk){
							iSucessCount = iSucessCount+1;
						}else{
						  iErrorCount = iErrorCount+1;
						  tipMessage.append("新增保存失败").append(userDto.getUserCode()).append(",");
						}
					}else {//存在修改
						BeanUtils.copyProperties(user,userDto);
						userDto.setPassword(null);//密码置空 保证修改的时候不改变

						Integer deptId = sysDeptJd(data);
						if(deptId == null){
							iErrorCount = iErrorCount+1;
							tipMessage.append("修改部门id为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setDeptId(deptId);//部门id

						String lineCode = lineCodeJd(data);
						if(StringUtils.isEmpty(lineCode)){
							iErrorCount = iErrorCount+1;
							tipMessage.append("修改线路编号为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setLineCode(lineCode);//管辖线路
						userDto.setStationCode("");//管辖站点默认空字符串
						userDto.setDeviceOperateNo("");//设备操作号默认空字符串

						List<Integer> roleList = roleListJd(data);
						userDto.setRole(roleList);//角色id
						userDto.setIsRecordChange("0");//不记录历史记录
						boolean isOk = userService.updateUser(userDto);
						if(isOk){
							iSucessCount = iSucessCount+1;
						}else{
							iErrorCount = iErrorCount+1;
						    tipMessage.append("修改保存失败").append(userDto.getUserCode()).append(",");
						}

					}
				}

			}
		}
		if(tipMessage!=null && tipMessage.length()>0 && iErrorCount>0){			
			String message = "";
			if(iSucessCount==0){
			    message = "全部导入失败";
			}else{
			     message = "部分导入成功" +String.valueOf(iSucessCount)+"条.失败"+String.valueOf(iErrorCount) +"条"; 
				 LOGGER.info("机电导入用户失败信息:{}", message+tipMessage.toString());
				 saveUserImportlog("机电用户",message+tipMessage.toString());
				//message = message+tipMessage.toString();
			}		   
			throw new CheckedException(message);
		}
		return R.ok();
	}

	/**
	 * 下载客运模板
	 * @param
	 * @return
	 * @throws
	 */
	@ApiOperation(value = "下载客运模板", notes = "下载客运模板")
	@GetMapping("/exportTamplateKY")
	public void exportTamplateKY(HttpServletResponse response) {
		userService.exportTamplatesKY(response);
	}
	/**
	 * 导入客运用户信息
	 *
	 * @param file
	 * @return
	 */
	@ApiOperation(value = "导入客运用户信息", notes = "导入客运用户信息")
	@SysLog("导入客运用户信息")
	@PostMapping({ "/userImportKY" })
	public R userImportKY(@RequestParam("file") final MultipartFile file) throws Exception {

		final File excelFile = MultipartFileToFile.multipartFileToFile(file);
		List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(1).doReadSync();
		StringBuilder tipMessage = new StringBuilder();
		int iSucessCount = 0;
		int iErrorCount = 0;
		if (CollectionUtil.isNotEmpty(listMap)) {
			MultipartFileToFile.delteTempFile(excelFile);
			for (int m = 0; m < listMap.size(); m++) {
				Map<Integer, String> data = listMap.get(m);
				// 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
				LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

				UserDTO userDto = new UserDTO();

				if(StringUtils.isNotEmpty(data.get(2).trim())){

					//根据userCode先判断用户表中用户是否存在
					SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery()
							.eq(SysUser::getUsername, data.get(2).trim())
							.eq(SysUser::getDelFlag,"0"));
					//不存在添加
					if(ObjectUtil.isEmpty(user)){
						userDto.setNikename(data.get(1));//角色名
						userDto.setUsername(data.get(2).trim());
						userDto.setUserCode(data.get(2).trim());
						userDto.setPassword(defaultPassword);//默认密码

						Integer deptId = sysDeptKy(data);
						if(deptId == null){
							iErrorCount = iErrorCount+1;
							tipMessage.append("新增部门id为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setDeptId(deptId);//部门id

						userDto.setLockFlag("0");//账号锁定状态
						userDto.setBelongToLine(false);//默认不是线网人员

						String lineCode = lineCodeKy(data);
						if(StringUtils.isEmpty(lineCode)){
							iErrorCount = iErrorCount+1;
							tipMessage.append("新增线路编号为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setLineCode(lineCode);//管辖线路

						String stationCode = stationCodeKy(data,lineCode);
						if(StringUtils.isEmpty(stationCode)){
							iErrorCount = iErrorCount+1;
							tipMessage.append("新增车站编号为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setStationCode(stationCode);//管辖车站

						if(StringUtils.isNotEmpty(data.get(3))){
							//正则校验
							String operateNo = RegExUtilOrString.getPattern(data.get(3));
							userDto.setDeviceOperateNo(operateNo);//设备操作号
							//设备操作号添加到参数表
							remoteSupportService.insertDeviceOperation(lineCode,stationCode,operateNo);
						}

						List<Integer> roleList = roleListKy(data);
						userDto.setRole(roleList);//角色id
						userDto.setIsRecordChange("0");//不记录历史记录
						boolean isOk  = userService.saveUser(userDto);
						if(isOk){
							iSucessCount = iSucessCount+1;
						}else{
						  iErrorCount = iErrorCount+1;
						  tipMessage.append("新增保存失败").append(userDto.getUserCode()).append(",");
						}
					}else {//存在修改
						BeanUtils.copyProperties(user,userDto);
						userDto.setPassword(null);//密码置空 保证修改的时候不改变

						Integer deptId = sysDeptKy(data);
						if(deptId == null){
							iErrorCount = iErrorCount+1;
							tipMessage.append("修改部门id为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setDeptId(deptId);//部门id

						String lineCode = lineCodeKy(data);
						if(StringUtils.isEmpty(lineCode)){
							iErrorCount = iErrorCount+1;
							tipMessage.append("修改线路编号为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setLineCode(lineCode);//管辖线路
						userDto.setStationCode("");//管辖站点默认空字符串

						String stationCode = stationCodeKy(data,lineCode);
						if(StringUtils.isEmpty(stationCode)){
							iErrorCount = iErrorCount+1;							
							tipMessage.append("修改车站编号为空").append(userDto.getUserCode()).append(",");
							continue;
						}
						userDto.setStationCode(stationCode);//管辖车站

						if(StringUtils.isNotEmpty(data.get(3))){
							//正则校验
							String operateNo = RegExUtilOrString.getPattern(data.get(3));
							userDto.setDeviceOperateNo(operateNo);//设备操作号
							//设备操作号添加到参数表
							remoteSupportService.insertDeviceOperation(lineCode,stationCode,operateNo);
						}

						List<Integer> roleList = roleListKy(data);
						userDto.setRole(roleList);//角色id
						userDto.setIsRecordChange("0");//不记录历史记录
						boolean isOk  = userService.updateUser(userDto);
						if(isOk){
							iSucessCount = iSucessCount+1;
						}else{
						  iErrorCount = iErrorCount+1;
						  tipMessage.append("修改保存失败").append(userDto.getUserCode()).append(",");
						}


					}
				}

			}
		}
		if(tipMessage!=null && tipMessage.length()>0 && iErrorCount > 0){
		   String message = "";
			if(iSucessCount==0){
			    message = "全部导入失败";
				LOGGER.info("客运导入用户失败信息:{}", message+tipMessage.toString());
				saveUserImportlog("客运用户",message+tipMessage.toString());
			}else{
			    message = "部分导入成功" +String.valueOf(iSucessCount)+"条.失败"+String.valueOf(iErrorCount) +"条"; 
				//message = message+tipMessage.toString();
				LOGGER.info("客运导入用户失败信息:{}", message+tipMessage.toString());
				saveUserImportlog("客运用户",message+tipMessage.toString());
			}		   
			throw new CheckedException(message);

		}
		
		return R.ok();
	}

	//机电查部门id
	private Integer sysDeptJd(Map<Integer, String> data) {
		if(StringUtils.isNotEmpty(data.get(3))){
			String deptName = data.get(3).trim();//.substring(4); 导入用户部门名称直接写最后一级不用再截取
			SysDept sysDept = sysDeptService.getOne(Wrappers.<SysDept>lambdaQuery()
					.eq(SysDept::getName, deptName)
					.eq(SysDept::getDelFlag,"0"));
			if(ObjectUtil.isNotEmpty(sysDept)){
				return sysDept.getDeptId();
			}else {
				return null;
			}
		}
		return null;
	}

	//机电查管辖线路
	private String lineCodeJd(Map<Integer, String> data) {
		if(StringUtils.isNotEmpty(data.get(4))){
			String name = data.get(4).trim();
			String lineCode = remoteSupportService.getCodeByName(name).getData();
			return lineCode;
		}
		return "";
	}

	//机电查角色id
	private List<Integer> roleListJd(Map<Integer, String> data) {
		List<Integer> roleList = new ArrayList<>();
		if(StringUtils.isNotEmpty(data.get(6))){
			SysRole sysRole = sysRoleService.getOne(Wrappers.<SysRole>lambdaQuery()
					.eq(SysRole::getRoleName, data.get(6).trim())
					.eq(SysRole::getDelFlag,"0"));
			if(ObjectUtil.isNotEmpty(sysRole)){
				roleList.add(sysRole.getRoleId());
				return roleList;
			}else {
				return null;
			}
		}
		return null;
	}

	//客运查部门id
	private Integer sysDeptKy(Map<Integer, String> data) {
		if(StringUtils.isNotEmpty(data.get(5))){
			String deptName = data.get(5).trim();//.substring(4); 导入用户部门名称直接写最后一级不用再截取
			SysDept sysDept = sysDeptService.getOne(Wrappers.<SysDept>lambdaQuery()
					.eq(SysDept::getName, deptName)
					.eq(SysDept::getDelFlag,"0"));
			if(ObjectUtil.isNotEmpty(sysDept)){
				return sysDept.getDeptId();
			}else {
				return null;
			}
		}
		return null;
	}

	//客运查管辖线路
	private String lineCodeKy(Map<Integer, String> data) {
		if(StringUtils.isNotEmpty(data.get(6))){
			String name = data.get(6).trim();
			String lineCode = remoteSupportService.getCodeByName(name).getData();
			return lineCode;
		}
		return "";
	}

	//客运查管辖车站
	private String stationCodeKy(Map<Integer, String> data, String lineCode) {
		if(StringUtils.isNotEmpty(data.get(7))) {
			String name = data.get(7).trim();
			String stationCode = remoteSupportService.getCodeByNameAndLineCode(name, lineCode).getData();
			return stationCode;
		}
		return "";
	}	

	//客运查角色id
	private List<Integer> roleListKy(Map<Integer, String> data) {
		List<Integer> roleList = new ArrayList<>();
		if(StringUtils.isNotEmpty(data.get(8))) {
			SysRole sysRole = sysRoleService.getOne(Wrappers.<SysRole>lambdaQuery()
					.eq(SysRole::getRoleName, data.get(8).trim())
					.eq(SysRole::getDelFlag, "0"));
			if (ObjectUtil.isNotEmpty(sysRole)) {
				roleList.add(sysRole.getRoleId());
				return roleList;
			} else {
				return null;
			}
		}
		return null;
	}

	private boolean saveUserImportlog(String type,String errorRemark){
		SysUserImportlog log = new SysUserImportlog();
		log.setType(type);
		log.setErrorRemark(errorRemark);
		//log.setImportDate(DateFormat.);
		sysUserImportlogService.save(log);
		return true;

	}
}
